import datetime
import os

from flask import Flask, make_response, request, session

app = Flask(__name__)

# 启用session
app.config['SECRET_KEY'] = os.urandom(24) # 生成随机数种子，用于生成sessionId

@app.route('/')
def hello_world():
    return "<p style='color:red;'>Hello World 你好世界222</p>"

@app.route('/cookie')
def cookie():
    response = make_response("设置cookie成功")
    # response.set_cookie("name", "join sex", max_age=3)
    dt = datetime.datetime.today() + datetime.timedelta(days=1)
    response.set_cookie("name", "leixiangxi", expires=dt)
    response.set_cookie("sex", "male", expires=dt)
    response.set_cookie("age", "32", expires=dt)
    return response

@app.route('/get_cookie')
def get_cookie():
    cookies = request.cookies
    # 单独获取
    print(cookies.get("age"))
    cookies_dict = cookies.to_dict()
    for k,v in cookies_dict.items():
        print(k,v)

    return "hello world"

@app.route('/del_cookie')
def del_cookie():
   response = make_response("删除cookie成功")
   # response.delete_cookie("name")
   # 批量删除cookie
   cookies = request.cookies
   cookies_dict = cookies.to_dict()
   for k, v in cookies_dict.items():
    response.delete_cookie(k)
    return response


# 添加session
@app.route('/add_session')
def add_session():
    session['username'] = 'leixiangxi'
    session['age'] = '30'
    return "添加session成功"

# 获取session
@app.route('/get_session')
def get_session():
    print(session.keys())
    print(session.get('username'))
    return "session 获取成功" + session.get('username')

# 删除session
@app.route('/del_session')
def del_session():
    session.clear()
    return "删除session成功"

if __name__ == '__main__':
    app.run(debug=True)